# config/__init__.py - 配置文件
import os
import logging
from typing import Optional

# 配置日志
logger = logging.getLogger("RAG")

# ========== 配置常量 ==========
# API配置
BAILIAN_API_KEY_NAME = "BAILIAN_API_KEY"

# 模型配置
EMBEDDING_MODEL = "text-embedding-v2"
LLM_MODEL = "qwen-plus"
LLM_TEMPERATURE = 0.1
LLM_MAX_TOKENS = 300
LLM_TIMEOUT = 30

# 文件路径配置
RESOURCE_PATH = "resource/regulations"
NLTK_DATA_DIR = os.path.join(os.path.expanduser('~'), 'nltk_data')

# ========== 配置函数 ==========
def load_api_key(key_name: str = None) -> Optional[str]:
    """
    安全加载API密钥
    
    Args:
        key_name: 密钥名称，默认为BAILIAN_API_KEY
        
    Returns:
        API密钥字符串，如果未找到则返回None
    """
    if key_name is None:
        key_name = BAILIAN_API_KEY_NAME
        
    # 1. 优先从环境变量获取
    api_key = os.getenv(key_name)
    if api_key:
        logger.debug(f"从环境变量加载 {key_name}")
        return api_key
        
    # 2. 从api_key.txt文件获取
    try:
        api_key_file = os.path.join(os.path.dirname(__file__), '..', 'api_key.txt')
        with open(api_key_file, 'r', encoding='utf-8') as f:
            api_key = f.read().strip()
            if api_key:
                logger.info(f"从文件加载 {key_name}")
                return api_key
    except FileNotFoundError:
        logger.debug(f"未找到API密钥文件: {api_key_file}")
    except Exception as e:
        logger.warning(f"读取API密钥文件失败: {e}")
        
    # 3. 尝试从.env文件加载
    try:
        from dotenv import load_dotenv
        load_dotenv()
        api_key = os.getenv(key_name)
        if api_key:
            logger.info(f"从.env文件加载 {key_name}")
            return api_key
    except ImportError:
        logger.debug("python-dotenv未安装，跳过.env文件加载")
    except Exception as e:
        logger.warning(f"加载.env文件失败: {e}")
        
    logger.error(f"未找到API密钥: {key_name}")
    return None

def validate_config() -> bool:
    """
    验证配置是否完整
    
    Returns:
        bool: 配置是否有效
    """
    # 验证API密钥
    api_key = load_api_key()
    if not api_key:
        logger.error("API密钥未配置")
        return False
        
    # 验证资源目录
    if not os.path.exists(RESOURCE_PATH):
        logger.error(f"资源目录不存在: {RESOURCE_PATH}")
        return False
        
    if not os.listdir(RESOURCE_PATH):
        logger.error(f"资源目录为空: {RESOURCE_PATH}")
        return False
        
    logger.info("配置验证通过")
    return True

def get_model_config() -> dict:
    """
    获取模型配置字典
    
    Returns:
        dict: 模型配置
    """
    return {
        "embedding_model": EMBEDDING_MODEL,
        "llm_model": LLM_MODEL,
        "temperature": LLM_TEMPERATURE,
        "max_tokens": LLM_MAX_TOKENS
    }

def setup_nltk() -> bool:
    """
    设置NLTK环境，避免重复下载
    
    Returns:
        bool: 设置是否成功
    """
    try:
        # 添加NLTK数据路径
        nltk_data_dir = NLTK_DATA_DIR
        if not os.path.exists(nltk_data_dir):
            os.makedirs(nltk_data_dir)
        
        import nltk
        nltk.data.path.append(nltk_data_dir)
        
        # 检查必要的数据包，只在缺失时下载
        required_packages = [
            ('tokenizers/punkt', 'punkt'),
            ('tokenizers/punkt_tab', 'punkt_tab'),
        ]
        
        downloaded = False
        for data_path, package_name in required_packages:
            try:
                nltk.data.find(data_path)
                logger.debug(f"NLTK {package_name} 已存在")
            except LookupError:
                logger.debug(f"下载 NLTK {package_name}...")
                try:
                    nltk.download(package_name, quiet=True, download_dir=nltk_data_dir)
                    logger.debug(f"NLTK {package_name} 下载完成")
                    downloaded = True
                except Exception as e:
                    logger.warning(f"下载 NLTK {package_name} 失败: {e}")
        
        if downloaded:
            logger.debug("NLTK数据包下载完成")
        else:
            logger.debug("NLTK数据包已就绪")
            
        logger.debug(f"NLTK数据目录设置: {nltk_data_dir}")
        return True
    except Exception as e:
        logger.warning(f"NLTK设置失败: {e}")
        return False

def setup_ssl() -> bool:
    """
    设置SSL环境（解决SSL连接问题）
    
    Returns:
        bool: 设置是否成功
    """
    try:
        import ssl
        ssl._create_default_https_context = ssl._create_unverified_context
        logger.debug("SSL验证已禁用（用于测试环境）")
        return True
    except Exception as e:
        logger.warning(f"SSL设置失败: {e}")
        return False
    
def setup_logging(level: int = logging.INFO) -> None:
    """
    设置日志配置
    
    Args:
        level: 日志级别，默认INFO
    """
    
    # 禁用不必要的日志和警告
    import logging
    import warnings
    logging.getLogger("llama_index").setLevel(logging.ERROR)
    logging.getLogger("posthog").setLevel(logging.ERROR)
    logging.getLogger("urllib3").setLevel(logging.ERROR)
    warnings.filterwarnings("ignore")
    
    logging.basicConfig(
        level=level,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
def setup_base_net() -> None:
    """
    设置基础网络环境，禁用所有遥测和网络连接尝试
    """
    import os
    os.environ["LLAMA_TELEMETRY"] = "0"
    os.environ["DISABLE_TELEMETRY"] = "1"
    os.environ["DO_NOT_TRACK"] = "1"
    os.environ["ANONYMIZED_TELEMETRY"] = "False"